<?php

namespace App\Service;

use App\Context\UserInfoContext;
use App\Model\AdminUserAction;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\Context;

class AdminLogService {

    public function __construct(RequestInterface $request, $routerConfig) {
        $userInfoContext = Context::get(UserInfoContext::class);

        $adminUserAction = new AdminUserAction();
        $adminUserAction->action_name = $routerConfig['title'];
        $adminUserAction->uid = $userInfoContext->userInfo['id'];
        $adminUserAction->nickname = empty($userInfoContext->userInfo['nickname']) ? '' : $userInfoContext->userInfo['nickname'];
        $adminUserAction->add_time = time();
        $adminUserAction->url = $routerConfig['url'];
        $adminUserAction->data = json_encode($request->all());
        $adminUserAction->ip = $this->getIp($request); // 获取客户端IP

        $adminUserAction->save();
    }

    /**
     * 获取客户端IP
     * @param RequestInterface $request
     * @return array|string|null
     */
    public function getIp(RequestInterface $request): array|string|null {
        $headers = $request->getHeaders();

        if (isset($headers['x-forwarded-for'][0]) && !empty($headers['x-forwarded-for'][0])) {
            return $headers['x-forwarded-for'][0];
        }

        if (isset($headers['x-real-ip'][0]) && !empty($headers['x-real-ip'][0])) {
            return $headers['x-real-ip'][0];
        }

        $serverParams = $request->getServerParams();

        return $serverParams['remote_addr'] ?? '';
    }
}